/*
 * @Author: silence silence9685@163.com
 * @Date: 2023-06-15 09:31:25
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-04-15 10:40:10
 * @FilePath: \ems_neutral_app\lib\pages\Devices\PowerStation\PowerStationAddPage.dart
 * @Description: 添加电站
 */
import 'package:ems_neutral_app/base/SilScaffold.dart';
import 'package:ems_neutral_app/common/widgets/cubitWidget/DividingLine.dart';
import 'package:ems_neutral_app/common/widgets/cubitWidget/SettingItem.dart';
import 'package:ems_neutral_app/utils/color/ColorUtils.dart';
import 'package:ems_neutral_app/utils/router/ARouter.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sil_base_widget_package/sil_base_widget_package.dart';
import 'package:sil_utils_package/sil_utils_package.dart';

import '../../../../common/module/Scan/ScanPage.dart';
import '../../../../common/widgets/cubitWidget/BottomSheetView.dart';
import '../../../base/SilAppBar.dart';
import '../../../bloc/userbloc/user_bloc.dart';
import '../../../main.dart';
import '../../Mine/Language/SilLocalizations/SilLocalizations.dart';
import '../Controller/PowerStationAddController.dart';

class PowerStationAddPage extends StatefulWidget {
  final bool navBarHide;
  const PowerStationAddPage({this.navBarHide = false, super.key});

  @override
  State<PowerStationAddPage> createState() => _PowerStationAddPageState();
}

class _PowerStationAddPageState extends State<PowerStationAddPage> {
  int _deviceType = 1; // 1高压 2低压

  /// 设备型号
  late List<String> _deviceModelList;
  int? _curDeviceModel;

  /// 时区
  List<String> _timeZoneList = [];
  int? _curDtimeZone;

  /// SN码
  String? _SNCode;
  PowerStationAddController _controller = Get.put(PowerStationAddController());

  /// 经纬度
  double _locationLng = 0.0;
  double _locationLat = 0.0;

  /// 是否显示底部添加SN码视图
  bool _isaddSNDz = false;

  late ValueKey _snTextFieldKey;

  /// 思道尔设备Key
  String? _sDErKey;

  @override
  void initState() {
    super.initState();

    Future.delayed(Duration.zero, () {
      /// 获取设备型号
      getDeviceModels();

      /// 获取定位
      getLocation();

      /// 获取时区列表
      getTimZoneList();
    });

    _snTextFieldKey = ValueKey(SilTimeUtils.currentTimeMillis());
  }

  /// 获取设备型号
  getDeviceModels() async {
    this._deviceModelList =
        await _controller.getDeviceModels(equipmentSelection: _deviceType);
  }

  /// 获取定位
  getLocation() {
    _controller.getLocation().then((position) {
      if (position != null) {
        _locationLng = position.longitude;
        _locationLat = position.latitude;
      }

      SilLog.d("_locationLng:${_locationLng};;; _locationLat:${_locationLat}");
    });
  }

  /// 获取时区名称列表
  getTimZoneList() {
    _controller.getTimeZoneNameList(
      context: context,
      successHandler: (p0) {
        _timeZoneList = p0;
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return SilScaffold(
      title: LangOf(context)?.dzdz2?.add_power,
      navBarHide: widget.navBarHide,
      body: mainWidget(),
      sideMargin: 0,
      backButtonFunc: handlerAction,
    );
  }

  handlerAction() async {
    /// 没有设备时，可以退出app或者换个账号登录
    if (SilTools.stringIsEmpty(UserBlocTool.userEntity?.powerRecordId) ||
        UserBlocTool.userEntity?.powerRecordId == '0') {
      signOutPrompt();
    } else {
      ARoute.pop(context);
    }
  }

  /// 退出登录确认提示
  signOutPrompt() {
    SilAlertDialog.showAlertDialog(
        context,
        SilAlertDialogData(
          title: LangOf(context)?.mine?.logout, //'温馨提示',
          cancelButtonTitle: LangOf(context)?.common?.cancel, //'取消',
          confrimButtonTitle: LangOf(context)?.common?.confirm, //'确认',
          content: LangOf(context)?.mine?.logoutDesc, //'是否退出登录'
        ), confrimFunc: () async {
      UserBlocTool.loginOut(navigatorKey.currentState!.context);
      if (Navigator.canPop(context)) Navigator.pop(context);
    });
  }

  mainWidget() {
    String? stationType = null;
    if (_curDeviceModel != null) {
      String type = _deviceModelList[_curDeviceModel!];
      stationType = (type.contains('E3')) ? stationType = 'e3' : type;
    }

    return Container(
      alignment: Alignment.bottomCenter,
      child: Stack(
        alignment: Alignment.center,
        children: [
          SilImage(
            stationType == 'e3'
                ? 'imgs/set/set_add_bg_e3.png'
                : 'imgs/set/set_add_bg.png',
            fit: BoxFit.fill,
            height: MediaQuery.of(context).size.height,
          ),

          /// 添加SN码按钮
          Container(
            child: centerAddSNButton(),
            alignment: Alignment.center,
          ),

          /// 添加SN码视图
          if (_isaddSNDz)
            Positioned(left: 0, right: 0, bottom: 0, child: showBottomView()),

          /// 如果隐藏了导航条，返回需要自定义处理
          if (widget.navBarHide)
            Positioned(left: 0, right: 0, top: 44, child: topNavView()),
        ],
      ),
    );
  }

  /// 顶部信息
  topNavView() {
    return Container(
      margin: EdgeInsets.only(
          top: MediaQuery.of(context).padding.top, bottom: 30.w),
      child: SilAppBar(
        backgroundColor: Colors.transparent,
        leadingWidget:
            SilScaffoldButton.backButtonStatic(context, onTap: handlerAction),
        titleWidget: SilScaffoldButton.titleView(
            title: LangOf(context)?.dzdz2?.add_power),
      ),
    );
  }

  /// 中间添加SN码按钮
  centerAddSNButton() {
    return ConstrainedBox(
      constraints: BoxConstraints(minWidth: 200.w, maxHeight: 45.w),
      child: SilEmptyButton(
        useConstrained: true,
        backgroundColor: Color.fromRGBO(0, 0, 0, 0.3),
        borderColor: ColorUtils.hexColor('#767a7f'),
        borderWidth: 0.5.w,
        radius: 8.w,
        margin: EdgeInsets.symmetric(vertical: 1.w, horizontal: 50.w),
        child: SilText(LangOf(context)?.dzdz2?.sn_code,
            fontSize: 19.sp, color: ColorUtils.color_font_main),
        onTapFunc: () {
          setState(() {
            _isaddSNDz = true;
          });
        },
      ),
    );
  }

  /// 显示底部添加SN码视图
  showBottomView() {
    return Container(
      // height: (375 + 50).w,
      decoration: BoxDecoration(
          color: Colors.black,
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(16.w), topRight: Radius.circular(16.w))),
      child: contentView(),
    );
  }

  contentView() {
    return Column(
      children: [
        /// 顶部操作按钮
        topHandlerBtnsView(),

        /// 设备类型
        deviceTypeView(),

        /// 设备型号
        deviceModelView(),

        /// 时区选择
        chooseTimeZoneView(),

        /// 设备SN码
        deviceCodeView(),

        /// 是否是思道尔设备
        sDErTypeView(),
      ],
    );
  }

  /// 顶部按钮
  topHandlerBtnsView() {
    String modelSelection =
        (_curDeviceModel != null) ? _deviceModelList[_curDeviceModel!] : "";

    return Stack(
      alignment: Alignment.center,
      children: [
        Container(
          child: Container(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                SilButton(
                  title: LangOf(context)?.common?.cancel,
                  titleColor: ColorUtils.hexColor('#848484'),
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w500,
                  padding:
                      EdgeInsets.symmetric(horizontal: 15.w, vertical: 10.w),
                  onTapFunc: () {
                    setState(() {
                      _isaddSNDz = false;
                    });
                  },
                ),
                SilButton(
                  title: LangOf(context)?.common?.confirm,
                  titleColor: ColorUtils.hexColor('#F59A23'),
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w500,
                  padding:
                      EdgeInsets.symmetric(horizontal: 15.w, vertical: 10.w),
                  onTapFunc: () {
                    _controller.powerStationAdd(
                        context: context,
                        snNumber: _SNCode ?? "",
                        modelSelection: modelSelection,
                        equipmentSelection: _deviceType,
                        timeZoneIndex: _curDtimeZone ?? 0,
                        locationLng: _locationLng,
                        locationLat: _locationLat,
                        userId: UserBlocTool.userEntity?.id,
                        key: _sDErKey,
                        successHandler: (p0) {
                          // 设备添加成功
                          if (Navigator.canPop(context)) Navigator.pop(context);
                        });
                  },
                ),
              ],
            ),
          ),
          padding: EdgeInsets.symmetric(vertical: 15.w, horizontal: 20.w),
        ),
        Positioned(
          child: DividingLine(),
          bottom: 0,
          left: 0,
          right: 0,
        )
      ],
    );
  }

  /// 设备类型
  deviceTypeView() {
    return SettingItem(
        margin: EdgeInsets.symmetric(vertical: 15.w, horizontal: 10.w),
        lineHorizontalSpace: 10.w,
        title: LangOf(context)?.common?.equipmentSelection,
        rightView: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            SilButton(
              title: '  (3/4/5)kW  ',
              titleColor: (_deviceType == 2) ? Colors.white : Colors.black,
              backgroundColor: (_deviceType == 2)
                  ? ColorUtils.hexColor('#F59A23')
                  : Colors.white,
              radius: 4.w,
              padding: EdgeInsets.symmetric(vertical: 5.w, horizontal: 3.w),
              fontSize: 14.sp,
              onTapFunc: () {
                if (_deviceType != 2) setState(() => _deviceType = 2);
                getDeviceModels();
              },
            ),
            Padding(padding: EdgeInsets.only(right: 10.w)),
            SilButton(
              title: '(8/10/12)kW',
              titleColor: (_deviceType == 1) ? Colors.white : Colors.black,
              backgroundColor: (_deviceType == 1)
                  ? ColorUtils.hexColor('#F59A23')
                  : Colors.white,
              radius: 4.w,
              padding: EdgeInsets.symmetric(vertical: 5.w, horizontal: 3.w),
              fontSize: 14.sp,
              onTapFunc: () {
                if (_deviceType != 1) setState(() => _deviceType = 1);
                getDeviceModels();
              },
            ),
          ],
        ));
  }

  /// 设备型号
  deviceModelView() {
    return SettingItem(
      title: LangOf(context)?.common?.modelSelection,
      margin: EdgeInsets.symmetric(vertical: 15.w, horizontal: 10.w),
      lineHorizontalSpace: 10.w,
      subTitle: (_curDeviceModel != null)
          ? _deviceModelList[_curDeviceModel!]
          : LangOf(context)?.common?.modelNumber,
      onTapFunc: () {
        SilBottomSheet.show(
            context: context,
            child: BottomSheetView(
              initialSelectedItem: _curDeviceModel,
              titles: _deviceModelList,
              tapSureSeletedFunc: (selected) {
                setState(() {
                  _curDeviceModel = selected;
                });
              },
            ));
      },
    );
  }

  /// 时区选择
  chooseTimeZoneView() {
    return SettingItem(
      title: LangOf(context)?.common?.controySelection,
      margin: EdgeInsets.symmetric(vertical: 15.w, horizontal: 10.w),
      lineHorizontalSpace: 10.w,
      subTitle: (_curDtimeZone != null)
          ? _timeZoneList[_curDtimeZone!]
          : LangOf(context)?.common?.controySelection,
      onTapFunc: () {
        SilBottomSheet.show(
            context: context,
            child: BottomSheetView(
              initialSelectedItem: _curDtimeZone,
              titles: _timeZoneList,
              tapSureSeletedFunc: (selected) {
                setState(() {
                  _curDtimeZone = selected;
                });
              },
            ));
      },
    );
  }

  /// 设备SN码
  deviceCodeView() {
    return SettingItem(
        title: LangOf(context)?.common?.snNumber,
        margin: EdgeInsets.symmetric(vertical: 15.w, horizontal: 10.w),
        lineHorizontalSpace: 10.w,
        rightView: Row(mainAxisAlignment: MainAxisAlignment.end, children: [
          Container(
            width: 150.w,
            child: SilTextField(
              key: _snTextFieldKey,
              onValid: ((valid, value) {
                setState(() {
                  _SNCode = value;
                });
              }),
              hintText: LangOf(context)?.common?.enter,
              textAlign: TextAlign.end,
              textStyle: TextStyle(
                fontSize: 14.sp,
                color: ColorUtils.color_font_minor,
              ),
              interface: SilFormattersNickName(),
              text: _SNCode,
            ),
          ),
          SilButton(
            imgPath: 'imgs/common/common_scan.png',
            width: 24.w,
            height: 24.w,
            margin: EdgeInsets.only(left: 10.w),
            onTapFunc: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => ScanPage(),
                  )).then((value) {
                List<String> codeList =
                    _controller.recognitionScanSNCode(value);
                _SNCode = codeList[0];
                if (SilTools.stringIsEmpty(codeList[0]) == false) {
                  _sDErKey = codeList[1];
                }
                _snTextFieldKey = ValueKey(SilTimeUtils.currentTimeMillis());
                setState(() {});
              });
            },
          ),
        ]));
  }

  /// 是否是思道尔设备
  sDErTypeView() {
    Widget widget = Container();
    if (_controller.isSDErDevice(_SNCode) == false) {
      return Container();
    }

    widget = SettingItem(
        title: "KEY",
        margin: EdgeInsets.symmetric(vertical: 15.w, horizontal: 10.w),
        lineHorizontalSpace: 10.w,
        rightView: Row(mainAxisAlignment: MainAxisAlignment.end, children: [
          Container(
            width: 150.w,
            child: SilTextField(
              onValid: ((valid, value) {
                setState(() {
                  _sDErKey = value;
                });
              }),
              hintText: LangOf(context)?.dz_add?.addKey, //"请输入KEY",
              textAlign: TextAlign.end,
              textStyle: TextStyle(
                fontSize: 14.sp,
                color: ColorUtils.color_font_minor,
              ),
              interface: SilFormattersNickName(),
              text: _sDErKey,
            ),
          ),
        ]));
    return widget;
  }
}
